package com.tj.filter;

import com.alibaba.fastjson.JSON;
import com.sun.prism.impl.BaseContext;
import com.tj.controller.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("filter生效");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取login的session
        Object s = request.getSession().getAttribute("employee");

        //获取拦截URI
        String requestURI = request.getRequestURI();

        //定义不需要请求的路径
        String urls[]=new String[]{
                "/employee/login",
                "/employee/logout",
                "/front/**",
                "/backend/**",
                "/user/login",  // 移动端登录
                "/user/sendMsg",// 移动端发送短信
                "/common/**"
        };

        //判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //如果不需要处理，则放行
        if(check) {
            log.info("本次请求不需要处理");
            filterChain.doFilter(request,response);
            return ;
        }
        //判断pc端是否已登录(session)
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录");
            filterChain.doFilter(request,response);
            return ;
        }
        // 判断移动端是否已经登录
        if (request.getSession().getAttribute("user") != null){
            log.info("当前已经登录可进行操作，放行");
            filterChain.doFilter(request,response);
            return;
        }
        //失败则向客户端以输出流的方式发送数据
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean check(String[] urls, String requestURI) {
        for(String url:urls) {
            boolean match=pathMatcher.match(url,requestURI);
            if(match) return true;
        }
        return false;
    }
}
